package com.notepad.pages;

import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.util.AttributeSet;
import android.view.MotionEvent;
import android.view.View;

public class ColorPickerView extends View{

	public ColorPickerView(Context context, AttributeSet attrs) {
		super(context, attrs);
		initColorPickerView();
	}

	public ColorPickerView(Context context, AttributeSet attrs, int defStyle) {
		super(context, attrs, defStyle);
		// TODO Auto-generated constructor stub
		initColorPickerView();
	}

	private Paint mPaint;
	private int mCurrentX = 0, mCurrentY = 0, mCurrentZ = 0;
	private OnColorChangedListener mListener;
	
//	private static int[][][] areas = new int[128][128][128];
	Canvas canvas_v;

	private void initColorPickerView() {
//		for(int i =  0; i < 128; i++){
//			for(int j = 0; j< 128; j++){
//				for(int k = 0;k<128;k++){
//					areas[i][j][k] = Color.rgb(i*2, j*2, k*2);
//				}
//			}
//		}
		// Initializes the Paint that will draw the View
		mPaint = new Paint(Paint.ANTI_ALIAS_FLAG);
		mPaint.setTextAlign(Paint.Align.CENTER);
		mPaint.setTextSize(12);
	}
	
	public void setOnChangedListener(OnColorChangedListener listener){
		mListener = listener;
	}

	@Override
	protected void onDraw(Canvas canvas) {
		canvas_v = canvas;
		for(int i=0;i<128;i++){
			for(int j=0;j<128;j++){
				mPaint.setColor(Color.rgb(i*2,j*2,0));
				canvas.drawRect(i, j,i+1, j+1, mPaint);
			}
		}
		
		resetBarColor();
	}
	
	private void resetBarColor(){
		for(int i=127;i>=0;i--){
			if(i != mCurrentZ){
				mPaint.setColor(Color.rgb(mCurrentX*2, mCurrentY*2, i*2));
			}else{
				mPaint.setColor(Color.WHITE);
			}
			canvas_v.drawRect(130, 0, 150, i, mPaint);
		}
	}

	@Override
	protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
		setMeasuredDimension(150, 128);
	}

	@Override
	public boolean onTouchEvent(MotionEvent event) {
		if (event.getAction() != MotionEvent.ACTION_DOWN) return true;
		float x = event.getX();
		float y = event.getY();

		// If the touch event is located in the hue bar
		if (x > 0 && x < 128 && y > 0 && y < 128)
		{
			mCurrentX = (int)x;
			mCurrentY = (int)y;
			invalidate();
			resetBarColor();
			mListener.colorChanged(Color.rgb(mCurrentX*2, mCurrentY*2, mCurrentZ*2));
		}
		if(x > 130 && x <150 && y >0 && y < 128){
			mCurrentZ = (int)y;
			invalidate();
			resetBarColor();
			mListener.colorChanged(Color.rgb(mCurrentX*2, mCurrentY*2, mCurrentZ*2));
		}
		return true;
	}
	
	public int getSelectedColor(){
		return Color.rgb(mCurrentX*2, mCurrentY*2, mCurrentZ*2);
	}

}